from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel

from base.base_page import BasePageDTO
# 自定义模块导入
from config.db_sqlalchemy_config import get_db
from models.entity.employee_entity import Employee
from models.result import Result

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

router = APIRouter(
    prefix="/employee",
    tags=["员工管理"],
    dependencies=[Depends(oauth2_scheme)]
)


# Pydantic 模型用于定义请求体
class EmployeeCreate(BaseModel):
    name: str
    age: int
    department: str


class EmployeeSelect(BasePageDTO):
    name: Optional[str] = None
    age: Optional[int] = None


class EmployeeUpdate(BaseModel):
    name: Optional[str] = None
    age: Optional[int] = None
    department: Optional[str] = None


# 添加员工 - POST /employee/add
@router.post("/add",
             summary="新增员工信息",
             description="向系统中新增一名员工的信息。",
             response_description="新增成功返回员工数据",
             responses={
                 200: {"description": "操作成功",
                       "content": {"application/json": {"example": Result.ok(result={}, message="添加成功")}}},
                 500: {"description": "服务器内部错误",
                       "content": {"application/json": {"example": Result.error500(message="数据库异常")}}}
             })
def add_employee(employee: EmployeeCreate, db: Session = Depends(get_db)):
    # 创建数据库模型实例
    new_employee = Employee(**employee.dict())
    # 添加到数据库
    db.add(new_employee)
    # 提交事务
    db.commit()
    # 刷新对象
    db.refresh(new_employee)
    return Result.ok(result=new_employee, message="添加成功")


# 查询所有员工 - GET /employee/get
@router.get("/get_by_id",
            summary="根据Id查询员工信息",
            description="根据Id查询员工信息。",
            response_description="返回员工数据",
            responses={
                200: {"description": "操作成功",
                      "content": {"application/json": {"example": Result.ok(result=[], message="查询成功")}}},
                500: {"description": "服务器内部错误",
                      "content": {"application/json": {"example": Result.error500(message="数据库异常")}}}
            })
def get_employees(employee_id: str, db: Session = Depends(get_db)):
    employees = (db.query(Employee).filter(Employee.id == employee_id).all())
    return Result.ok(result=employees)


# 查询所有员工 - POST /employee/list
@router.post("/list",
             summary="分页获取获取所有员工信息",
             description="分页获取获取所有员工信息。",
             response_description="返回员工列表数据",
             responses={
                 200: {"description": "操作成功",
                       "content": {"application/json": {"example": Result.ok(result=[], message="查询成功")}}},
                 500: {"description": "服务器内部错误",
                       "content": {"application/json": {"example": Result.error500(message="数据库异常")}}}
             })
def list_employees(employee: EmployeeSelect, db: Session = Depends(get_db)):
    query = db.query(Employee)
    if employee.name:
        query = query.filter(Employee.name.like(f"%{employee.name}%"))
    if employee.age is not None or employee.age != 0:
        query = query.filter(Employee.age == employee.age)
    total = query.count()
    # 分页查询
    records = query.offset((employee.current - 1) * employee.size).limit(employee.size).all()
    result = {
        "total": total,
        "size": employee.size,
        "current": employee.current,
        "pages": (total + employee.size - 1) // employee.size,
        "records": records
    }
    return Result.ok(result=result)


# 更新员工 - PUT /employee/update/{employee_id}
@router.put("/update/{employee_id}",
            summary="更新员工信息",
            description="根据员工ID更新其信息（可部分更新）",
            response_description="更新成功返回更新后的员工数据",
            responses={
                200: {"description": "操作成功",
                      "content": {"application/json": {"example": Result.ok(result={}, message="更新成功")}}},
                404: {"description": "员工不存在",
                      "content": {"application/json": {"example": Result.error(404, message="员工不存在")}}},
                500: {"description": "服务器内部错误",
                      "content": {"application/json": {"example": Result.error500(message="数据库异常")}}}
            })
def update_employee(employee_id: int, employee: EmployeeUpdate, db: Session = Depends(get_db)):
    db_employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not db_employee:
        return Result.error(404, message="员工不存在")

    for key, value in employee.dict(exclude_unset=True).items():
        setattr(db_employee, key, value)

    db.commit()
    db.refresh(db_employee)
    return Result.ok(result=db_employee, message="更新成功")


# 删除员工 - DELETE /employee/delete/{employee_id}
@router.delete("/delete/{employee_id}",
               summary="删除指定员工",
               description="根据员工ID删除该员工记录。",
               response_description="删除成功后无内容返回",
               responses={
                   200: {"description": "操作成功",
                         "content": {"application/json": {"example": Result.ok(message="删除成功")}}},
                   404: {"description": "员工不存在",
                         "content": {"application/json": {"example": Result.error(404, message="员工不存在")}}},
                   500: dict(description="服务器内部错误",
                             content={"application/json": {"example": Result.error500(message="删除失败")}})
               })
def delete_employee(employee_id: int, db: Session = Depends(get_db)):
    db_employee = db.query(Employee).filter(Employee.id == employee_id).first()
    if not db_employee:
        return Result.error(404, message="员工不存在")

    try:
        db.delete(db_employee)
        db.commit()
        return Result.ok(message="删除成功")
    except Exception as e:
        db.rollback()
        return Result.error500(message=f"删除失败: {str(e)}")
